package dev.loong.boot3.controller;

import com.alibaba.excel.EasyExcel;
import dev.loong.boot3.pojo.User;
import dev.loong.boot3.service.UserService;
import dev.loong.boot3.vo.UserVo;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/users")
public class ExcelController {
    private final UserService userService;

    @Autowired
    public ExcelController(UserService userService) {
        this.userService = userService;
    }
    @GetMapping("/report")
    //@Async
    public void generateReport(HttpServletResponse response) throws IOException {
        System.out.println("报表线程名称：" + " [" + Thread.currentThread().getName() + "] ");
        Workbook workbook = new XSSFWorkbook();
        var sheet = workbook.createSheet("Report");
        var headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("用户名");
        headerRow.createCell(2).setCellValue("密码");

        var users = userService.findUsers(null, null);
        users.forEach(user -> {
            var row = sheet.createRow(sheet.getLastRowNum() + 1);
            row.createCell(0).setCellValue(String.valueOf(user.getId()));
            row.createCell(1).setCellValue(user.getUserName());
            row.createCell(2).setCellValue(user.getPwd());
        });
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");

        workbook.write(response.getOutputStream());
        workbook.close();
    }

    @GetMapping("/export-easy")
    public void exportWithEasyExcel(HttpServletResponse response) throws IOException {
        var users = userService.findUsers(null, null)
                .stream().map(UserVo::changeToVo).toList();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");
        EasyExcel.write(response.getOutputStream(), UserVo.class)
                .sheet("用户报表")
                .doWrite(users);
    }
}
